package com.heima.article.interceptor;

import com.heima.common.dto.User;
import com.heima.common.util.UserThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: itheima
 * @create: 2021-12-23 10:24
 */
@Component
public class UserInterceptor implements HandlerInterceptor {

    /**
     * 前置拦截（访问controller方法之前执行）
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.从网关转发而来请求 从请求头中获取用户ID
        String userId = request.getHeader("userId");
        String userName = request.getHeader("userName");
        //UserID 值如果为0 代表APP端用户没有登录"先看看"
        if(StringUtils.isNotBlank(userId) && !userId.equals("0")){
            //2.封装User对象将对象存入ThreadLocal方便后续web-service 取值
            User user = new User();
            user.setUserId(Integer.parseInt(userId));
            user.setUserName(userName);
            UserThreadLocalUtil.set(user);
        }
        return true;
    }

    /**
     * 后置拦截（controller方法调用完后）
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //TODO 将ThreadLocal中信息清除
        UserThreadLocalUtil.remove();
    }

    /**
     * 页面渲染完毕后拦截
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
